package controllers

import (
	"10.22/models"
	beego "github.com/beego/beego/v2/server/web"
)

type HouseController struct {
	beego.Controller
}
type JsonData struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *HouseController) Add() {
	name := c.GetString("name")
	menHao, _ := c.GetInt("menHao")
	types := c.GetString("types")
	price, _ := c.GetFloat("price", 64)
	area, _ := c.GetInt("area")
	house := models.House{
		Name:   name,
		MenHao: menHao,
		Types:  types,
		Price:  price,
		Area:   area,
	}
	err := models.DB.Create(&house).Error
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *HouseController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 3)
	name := c.GetString("name")
	house, total, err := models.MysqlList(page, pageSize, name)
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "分页列表失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData := make(map[string]interface{})
		pageData["house"] = house
		pageData["total"] = total
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "分页成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *HouseController) Del() {
	id, _ := c.GetInt("id")
	house := models.House{
		Id: id,
	}
	err := models.DB.Delete(&house).Error
	if err != nil {
		c.Data["json"] = JsonData{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonData{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
